//
//  FindViewController.m
//  geiTA
//
//  Created by 曲丹阳 on 14-11-19.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "FindViewController.h"
#import "FindSixCell.h"
#import "BackTableView.h"
#import "FindSixModel.h"
#import "FindDetailViewController.h"
#import "FindCell.h"
#import "FindBackDetailViewController.h"
#define CELLWIDTH self.view.frame.size.width / 2.2f
#define CELLHEIGHT self.view.frame.size.height / 6

@interface FindViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UITableViewDataSource,UITableViewDelegate>

@end

@implementation FindViewController
- (void)dealloc
{
    [_sixCellarray release];
    [_sixModelarray release];
    [_backarray release];
    [_collect release];
    [_table release];
    [_rightButton release];
    [_data release];
   
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController.navigationBar setTranslucent:NO];
    [self.navigationItem setTitle:@"发现"];
    
    [self createRightButton];
    [self createCollectionView];
    [self createChangeButton];
    
    [self creatLabel];
    
    [self randomUrl];
    
}

- (void)creatLabel
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width /1.4f,self.view.frame.size.height / 1.4f, 80, 20)];

    
    [label setFont:[UIFont systemFontOfSize:12]];
    [label setText:@"摇一摇有惊喜"];
    [self.collect addSubview:label];
    [label release];
    
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.sixModelarray = [NSMutableArray array];
        self.sixCellarray = [NSMutableArray array]; //存放小cell的数组
        self.backarray = [NSMutableArray array];    //翻转页面数组
        
        self.data = [NSData data];
        
    }
    return self;
}


- (void)randomUrl  //随机产生网址
{
    
    NSString *random = [NSString stringWithFormat: @"http://api.liwushuo.com/v1/channels/1/items?limit=6&offset=%u", arc4random() % 300];
    
    NSURL *strurl = [NSURL URLWithString:random];
    NSURLRequest *request = [NSURLRequest requestWithURL:strurl];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        self.data = data;
        [self createJson];
    }];
    
}

- (void)backUrl  //翻转页面网址
{
    NSString *urlstr = [NSString stringWithFormat:@"http://api.liwushuo.com/v1/collections?limit=12&offset=0"];
    NSURL *url = [NSURL URLWithString:urlstr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        self.data = data;
        [self createJsonBack];
    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.tabBarController.tabBar.hidden = NO;
}


#pragma mark -翻转按钮
- (void)createRightButton
{
    self.rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 32, 32)];
    [_rightButton setBackgroundImage:[UIImage imageNamed:@"find1.png"] forState:UIControlStateNormal];
    [_rightButton addTarget:self action:@selector(overTurnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:_rightButton];
    [self.navigationItem setRightBarButtonItem:item animated:YES];
    
    
}
#pragma mark -翻转响应
- (void)overTurnAction:(id)sender
{
    NSLog(@"翻转");
    
    
    if ([self.currentView isEqualToString:@"collection"]) { //比较翻转标识
        [self.navigationItem setTitle:@"全部专题"];
        [_rightButton setBackgroundImage:[UIImage imageNamed:@"find2.png"] forState:UIControlStateNormal];
        [self creatTable];
        [UIView transitionFromView:_collect toView:_table duration:1.0f options:UIViewAnimationOptionTransitionFlipFromRight completion:nil];
        self.currentView = @"table";
        
    } else {
        [self.navigationItem setTitle:@"发现"];
        [_rightButton setBackgroundImage:[UIImage imageNamed:@"find1.png"] forState:UIControlStateNormal];
        [UIView transitionFromView:_table toView:_collect duration:1.0f options:UIViewAnimationOptionTransitionFlipFromRight completion:nil];
        self.currentView = @"collection";
    }
    
}

#pragma mark -BackTableView
- (void)creatTable
{
    [self backUrl];
    
    self.table = [[BackTableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 49) style:UITableViewStylePlain];
    [self.table setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    _table.delegate = self;
    _table.dataSource = self;
    
    [_table release];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_backarray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *pool = @"backpool";
    FindCell *cell = [tableView dequeueReusableCellWithIdentifier:pool];
    if (!cell) {
        cell = [[FindCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:pool];
        
    }
    FindModel *model = [_backarray objectAtIndex:indexPath.row];
    cell.model = model;
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return tableView.frame.size.height / 3.8;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    FindBackDetailViewController *backdetail = [[FindBackDetailViewController alloc] init];
    FindModel *model = [_backarray objectAtIndex:indexPath.row];
    [backdetail GetId:model.id];
    [self.navigationController pushViewController:backdetail animated:YES];
    
    
}





#pragma mark -CollectionView
- (void)createCollectionView
{
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    [flow setItemSize:CGSizeMake(CELLWIDTH, CELLHEIGHT)]; //每个cell大小
    
    [flow setSectionInset:UIEdgeInsetsMake(self.view.frame.size.height/20, 10, 0, 10)]; //CollectionView距离上左下右距离
    [flow setMinimumLineSpacing:self.view.frame.size.height/25];
    [flow setMinimumInteritemSpacing:5];
    
    self.collect = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) collectionViewLayout:flow];
    
    self.currentView = @"collection"; //用于翻转的标识
    
    [_collect setBackgroundColor:[UIColor whiteColor]];
    
    _collect.dataSource = self;
    _collect.delegate = self;
    
    [_collect registerClass:[FindSixCell class] forCellWithReuseIdentifier:@"sixpool"];  //注册
    
    [self.view addSubview:_collect];
    [flow release];
    [_collect release];
    
    
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [_sixModelarray count];
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    FindSixCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"sixpool" forIndexPath:indexPath];
    
    FindSixModel *model = [_sixModelarray objectAtIndex:indexPath.item];
    cell.model = model;
    
    [_sixCellarray addObject:cell];
    
    return cell;
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    FindDetailViewController *detail = [[FindDetailViewController alloc] init];
    FindSixModel *mod = [_sixModelarray objectAtIndex:indexPath.item];
    
    [detail getdetailurlModel:mod];  //方法传值
    
    [self.navigationController pushViewController:detail animated:YES];
    
}


#pragma mark -换一批按钮
- (void)createChangeButton
{
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 35, self.view.frame.size.height /1.45, 70, 40)];
    
    [button setTitle:@"换一批" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    button.layer.cornerRadius = 10;
    button.layer.borderWidth = 1;
    
    [button addTarget:self action:@selector(changeAnotherAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.collect addSubview:button];
    
    [button release];
    
    
}

- (void)changeAnotherAction:(id)sender
{
    NSLog(@"换一批");
    
    for (FindSixCell *cell in _sixCellarray) {
        [cell flipOver];  //cell翻转
        
    }
    
    self.sixModelarray = [NSMutableArray array];
    self.sixCellarray = [NSMutableArray array];
    
    [self randomUrl];
   
}



#pragma mark -Json
- (void)createJson
{
    NSMutableDictionary *bigdic = [NSJSONSerialization JSONObjectWithData:_data options:NSJSONReadingMutableContainers error:nil];
    NSMutableDictionary *datadic = [bigdic objectForKey:@"data"];
    NSMutableArray *items = [datadic objectForKey:@"items"];
    
    for (NSMutableDictionary *smalldic in items) {
        FindSixModel *model = [[FindSixModel alloc] init];
        [model setValuesForKeysWithDictionary:smalldic];
        [_sixModelarray addObject:model];
    }
    
    [_collect reloadData];

}


- (void)createJsonBack
{
    NSMutableDictionary *bigdic = [NSJSONSerialization JSONObjectWithData:_data options:NSJSONReadingMutableContainers error:nil];
    NSMutableDictionary *data = [bigdic objectForKey:@"data"];
    NSMutableArray *collections = [data objectForKey:@"collections"];
    for (NSDictionary *smalldic in collections) {
        FindModel *model = [[FindModel alloc] init];
        [model setValuesForKeysWithDictionary:smalldic];
        [_backarray addObject:model];
    }
    [_table reloadData];
}


#pragma mark -摇一摇
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    NSLog(@"开始摇动手机");
}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    NSLog(@"停止摇动");
    
    self.sixModelarray = [NSMutableArray array];
    self.sixCellarray = [NSMutableArray array];
    [self randomUrl];
    
}
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    NSLog(@"取消");
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
